package com.lc1993929.mr.index;

import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.LongWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Job;
import org.apache.hadoop.mapreduce.Mapper;
import org.apache.hadoop.mapreduce.Reducer;
import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;
import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;

import java.io.IOException;

/**
 * Created by LiuChang on 2017/11/8/008.
 */
public class IndexStepTwo {

    static class IndexStepTwoMapper extends Mapper<LongWritable, Text, Text, Text> {
        @Override
        protected void map(LongWritable key, Text value, Context context) throws IOException, InterruptedException {
            String line = value.toString();
            String[] split = line.split("-");
            String word = split[0];
            String[] tmp = split[1].split("\t");
            String fileName = tmp[0];
            String count = tmp[1];

            context.write(new Text(word), new Text(fileName + "-->" + count));
        }
    }

    static class IndexStepTwoReducer extends Reducer<Text, Text, Text, Text> {
        @Override
        protected void reduce(Text key, Iterable<Text> values, Context context) throws IOException, InterruptedException {
            StringBuilder sb = new StringBuilder();
            for (Text value : values) {
                sb.append(value.toString()).append(" ");
            }
            context.write(key, new Text(sb.toString()));
        }
    }

    public static void main(String[] args) throws IOException, ClassNotFoundException, InterruptedException {
        Configuration conf = new Configuration();
        Job job = Job.getInstance(conf);
        //要执行的jar文件
        job.setJarByClass(IndexStepTwo.class);
        //指定mapper类和reducer类
        job.setMapperClass(IndexStepTwoMapper.class);
        job.setReducerClass(IndexStepTwoReducer.class);
        //指定mapper和reducer的输出的key和value的数据类型
        //job.setMapOutputKeyClass(Text.class);
        //job.setMapOutputValueClass(Text.class);
        //如果map阶段输出的kv的类型和reduce阶段输出kv类型完全一致，上面2行可省略
        job.setOutputKeyClass(Text.class);
        job.setOutputValueClass(Text.class);
        //指定要解析的文件类型，默认是TextInputFormat，可省略
        //job.setInputFormatClass(TextInputFormat.class);
        //指定要解析的文件路径
        FileInputFormat.setInputPaths(job, new Path(args[0]));
        //指定要输出的文件类型，默认是TextInputFormat，可省略
        //job.setOutputFormatClass(TextOutputFormat.class);
        //指定输出的文件路径
        FileOutputFormat.setOutputPath(job, new Path(args[1]));
        //设置分区计算规则
        job.setNumReduceTasks(Integer.parseInt(args[2]));

        // 向yarn提交job
        boolean res = job.waitForCompletion(true);

        System.exit(res ? 0 : 1);
    }
}
